/**
 * Created by Administrator on 2016/12/16.
 */

$(function () {
    init();
    loadInfo();
    uploadImg();
    $('input[type="text"]').attr('readonly', "readonly");//页面加载完成后，页面信息为只读状态
    $('.addTeam,.dealAll,.remove,.cancel,.resure').addClass("disabled");
}),
/*******点击编辑按钮，页面转换为可操作***********/
    $('.edit-style').click(function () {
        $('input[type="text"]').removeAttr('readonly');
        this.style.display = 'none';
        $('.addTeam,.dealAll,.remove,.cancel,.resure').removeClass("disabled");
    });
$(".form-date").datetimepicker(
    {
        language: "zh-CN",
        weekStart: 1,
        todayBtn: 1,
        autoclose: 1,
        todayHighlight: 1,
        startView: 2,
        minView: 2,
        forceParse: 0,
        format: "yyyy-mm-dd"
    });
/***弹出工地数据管理页面***/
$('.tab2Content2').click(function () {
    layer.open({
        title: '工地数据管理',
        shadeClose: true,
        shade: 0.8,
        type: 2,
        fix: false,
        maxmin: true,
        area: ['100%', '100%'],
        content: '../../../../siteData/siteDate.html'
    })
});
/*********弹出班组资金管理页面************/
$('.tab2Content3').click(function () {
    layer.open({
        title: '班组资金管理',
        shadeClose: true,
        shade: 0.8,
        type: 2,
        fix: false,
        maxmin: true,
        area: ['100%', '100%'],
        content: '../../edit/projectDetailsEdit/projectEdit.html'
    })
});
/*************弹出项目资金管理页面**************/
$('.tab2Content4').click(function () {
    layer.open({
        title: '项目资金管理',
        shadeClose: true,
        shade: 0.8,
        type: 2,
        fix: false,
        maxmin: true,
        area: ['100%', '100%'],
        content: '../../edit/projectDetailsEdit/projectEdit.html'
    })
});

/*********加载分包班组信息表***********/
function init() {
    $('#teamTable').bootstrapTable({
        url: `http://192.168.59.3:8082/console/projectInfo/findItemInfoByProjectCode?projectCode=${json.projectCode}&pageNum=1&pageSize=10`,
        onLoadSuccess: function (data) {
            console.log(data);
            $('.bs-checkbox').hide();
        },
        /*******点击查看编辑进入班组详情页面，并将后台数据同 步显示 在新页面上***************/
        onClickCell: function (field, value, row, $element) {
            console.log(row);
            var str = "";
            str += "projectCode=" + json.projectCode;
            for (var key in row) {
                str += "&" + key + "=" + row[key];
            }
            console.log(str);
            if (field == "add_remove") {
                layer.open({
                    title: '项目管理/项目详情/班组详情',
                    shadeClose: true,
                    shade: 0.8,
                    type: 2,
                    fix: false,
                    maxmin: true,
                    area: ['100%', '100%'],
                    content: `../teamDetailsView/teamDetails.html?${str}`,
                    end:function(){
                        $("#teamTable").bootstrapTable("refresh",`http://192.168.59.3:8082/console/projectInfo/findItemInfoByProjectCode?projectCode=${json.projectCode}&pageNum=1&pageSize=10`)
                    }
                })
            }
        },
    })
}
function responseHandler(res) {
    var needData = {
        rows: res.data.list,
        total: res.data.total
    }
    return needData;
}
function teamTableQuery(params) {
    params['pageNum'] = (params.offset / params.limit) + 1;
    params.pageSize = params.limit;
    return params;
}
function addRemoveFmt(index, row, val) {
    return "<button class='btn btn-info'>查看/编辑</button>"
}
function pjTypeFmt(index, row, val) {
    if (val == "1") {
        return "清包"
    } else {
        return "重包"
    }
};
/**********点击新增班组弹出新的页面*************/
$('.addTeam').click(function () {
    console.log(json.id);
    layer.open({
        title: '项目管理/新增项目/添加新班组',
        shadeClose: true,
        shade: 0.8,
        type: 2,
        fix: false,
        maxmin: true,
        area: ['100%', '100%'],
        content: `../../../addDetails/addTeams/addTeams.html?id=${json.id}&projectCode=${json.projectCode}`,
        end: function () {
            $('#teamTable').bootstrapTable("refresh", `http://192.168.59.3:8082/console/projectInfo/findItemInfoByProjectCode?projectCode=${json.projectCode}&pageNum=1&pageSize=10`)
        }
    })
});
/********点击批量删除显示表格的全选按钮**********/
$('.dealAll').click(function () {
    // console.log(this.innerHTML);
    if (this.innerHTML == "批量操作") {
        $('.bs-checkbox').show();
        this.innerHTML = "取消操作"

    } else {
        $('.bs-checkbox').hide();
        this.innerHTML = "批量操作";

    }
});
/************接收项目列表 主页面传过来的数据 并同步在项目详情子页面上**************/
var str = location.search;
var json = {};
str = str.slice(1).split("&");
//console.log(str);
for (var i = 0; i < str.length; i++) {
    var result = str[i].split('=');
    json[result[0]] = result[1];
    // console.log(json);
}
console.log(json);
function loadInfo() {
    $.ajax({
        type: 'put',
        url: `http://192.168.59.3:8082/console/projectInfo/getProjectInfoByCode/${json.projectCode}`,
        contentType: "application/json",
        success: function (obj) {
            console.log(obj);
            $.ajax({
                type: "get",
                contentType: 'application/json',
                url: 'http://192.168.59.3:8082/console/basedata/projectType/getAllProjectTypeList',
                success: function (data) {
                    console.log(data);
                    var oHtml = "";
                    console.log(data.data.length);
                    for (var i = 0; i < data.data.length; i++) {
                        oHtml += `<option value=${data.data[i].id}>${data.data[i].projectType}</option>`
                    }
                    $("[data-name='projectType']").html(oHtml);
                    $("[data-name]").each(function (i, e) {
                        // console.log(e);
                        if ($(e).attr("data-name") == "projectStart") {
                            $(e).val(getMyTime(obj.data.projectStart));
                        } else if ($(e).attr('data-name') == "projectType") {
                            $(e).val(obj.data[$(e).attr("data-name")])
                        } else {
                            $(e).val(obj.data[$(e).attr("data-name")])
                        }
                    })
                },
                error: function (err) {
                    console.log(err);
                }
            });
            //$("body").data(data);

        },
        error: function (err) {
            console.error(err.responseText);
        }

    });
}
////*********上传图片************///
function uploadImg() {
    var host = "http://192.168.59.2:7090/image";
    var firstName = "http://choosefine-uat.oss-cn-hangzhou.aliyuncs.com/";

    if ($('[data-pic]')) {
        $('[data-pic]')

            .html(`
            <img src="#">
            <form action=${host} method="post" enctype="multipart/form-data" target="hide_frame" style="display: none;">
              <input name="name">
              <input type="file" name="file"/>
            <form>
          `)
            .find('[type="file"]').on('change',
            function () {
                var lastName = "console/user/" + (new Date()).getTime() + '-' + this.files[0].name;
                $(this).prev().val(lastName);
                $(this).parent().submit();
                console.log(firstName + lastName);
                setTimeout(function () {
                    $(this).parent().prev().attr('src', firstName + lastName);
                }.bind(this), 12000)
            });
        $('[data-pic]')
            .each(function (i, div) {
                var dataName = $(div).attr('data-pic');

                $(div).find('img').attr('data-name', dataName)
            });

        $('[data-pic]').find('img')

            .on('click', function () {
                $(this).parent().find('[type="file"]').click();
            })

        $(document.body).append(`
            <iframe name="hide_frame" style="display: none">
          `)
    }

    if ($("[data-purl]")) {
        var images = $("[data-purl]").find('img');
        var purl = "";

        images.each(function (i, img) {
            purl = $(img).parent().attr('data-purl');
            $(img).attr('src', purl);
        })
    }
}
/********格式化日期*********/
function getMyTime(date) {
    date = new Date(date);
    var Y = date.getFullYear();
    var M = date.getMonth();
    var D = date.getDate();
    return `${Y}/${M}/${D}`
}
/***********点击按钮实现不同功能，点击删除则删除所选中数据***************/
$('.fixed-table-footer').on("click", "button", function (e) {
    var tId = $('.selected td:eq(1)').text();
    console.log(tId);
    if (this.innerHTML == "确定修改") {//当点击 完工的时候提交数据
        var oIpt = $('[data-name]');
        console.log(oIpt);
        var str = {};
        for (var i = 0; i < oIpt.length; i++) {
            //console.log(($(oIpt[i]).attr('data-name')));
            //console.log(oIpt[i].nodeName);
            if (oIpt[i].nodeName == "INPUT") {
                str[$(oIpt[i]).attr('data-name')] = $(oIpt[i]).val();
            };
            //console.log($(oIpt[i]).attr("data-name") == "contractorAuthorization");

            if ($(oIpt[i]).attr("data-name") == "contractorAuthorization") {
                var oA="";
                var a1=$(oIpt[i]).find("img");
                a1.each(function(i,e){
                    oA+=$(e).attr('src')+",";
                })
               oA = oA.slice(0,oA.length-1);
                str["contractorAuthorization"]=oA;
            };
            if ($(oIpt[i]).attr("data-name") == "constructAuthorization") {
                var oB="";
                var b1=$(oIpt[i]).find("img");
                b1.each(function(i,e){
                    oB+=$(e).attr('src')+",";
                })
                oB = oB.slice(0,oB.length-1);
                str["constructAuthorization"]=oB;
            };

        }
        str['projectStart'] = new Date(str.projectStart).getTime();
        str['id']=json.id;
        console.log(JSON.stringify(str));
        //多个项目ID之间用逗号分隔
        $.ajax({
            type: 'post',
            contentType: "application/json",
            dataType: "json",
            url: `http://192.168.59.3:8082/console/projectInfo/updateProjectInfo`,
            data: JSON.stringify(str),
            success: function (data) {
                console.log(data);
                //console.log($('.selected tr:eq(8)'));
                parent.layer.closeAll();
            },
            error: function (err) {
                console.log(err);
            }
        });
    }
    ;
    if (this.innerHTML == "删除") {//当点击删除的时候提交数据到后删除数据
        console.log(222);
        var oPid = $("#teamTable").data('bootstrap.table').options.data;

        $.ajax({
            type: 'put',
            contentType: "application/json",
            url: `http://192.168.59.3:8082/console/projectInfo/deleteTeam/${tId}`,
            data: '{"teamId":tId}',
            success: function (data) {
                console.log(data);
            },
            error: function (err) {
                console.log(err);
            }
        });
        $('.selected').remove();
    }
});
///////////////封装ajax //////////////////////////
function sendDigital(type, url, data) {
    $.ajax({
        type: type,
        url: url,
        data: data,
        contentType: 'application/json',
        success: function (data) {
            // console.log(data);
            localStorage.contractor = data;
        },
        error: function (err) {
            console.log(err);
        }
    });
}
/****点击项目承包人input框，弹出项目承包人列表页面*****/
$('input[data-name="contractorName"]').focus(function () {
    console.log(1);
    sendDigital('post', `http://192.168.59.3:8082/console/projectInfo/findUserListByRole`, '{"pageNum":1,"pageSize":6,"roleId":3}');
    layer.open({
        title: "项目承包人列表",
        type: 2,
        area: ['50%', '50%'],
        maxmin: true,
        fix: false,
        shadeClose: true,
        content: `../../../addDetails/addProject/contractor/contractor.html`
    });
    //console.log(localStorage.getItem("realName"));
});
$('input[data-name="contractorName"]').blur(function () {
    //$(this).val(sessionStorage.getItem("realName"));
    //sessionStorage.clear('realName');
    var moved = 0;
    var timer = setInterval(function () {
        moved++;
        if (sessionStorage.getItem("realName")) {
            this.value = sessionStorage.getItem("realName");
            clearInterval(timer);
            timer = null;
            sessionStorage.clear('realName');
        }
        if (moved >= 3) {
            clearInterval(timer);
            timer = null;
        }
    }.bind(this), 50)
})
/****点击承包单位input框，弹出承包单位列表页面*****/
$('input[data-name="constructionUnit"]').focus(function () {
    console.log(1);
    sendDigital('post', `http://192.168.59.3:8082/console/projectInfo/findCompanyByRole`, '{"pageNum":1,"pageSize":6,"roleId":4}');
    layer.open({
        title: "承包单位列表",
        type: 2,
        area: ['50%', '50%'],
        maxmin: true,
        fix: false,
        shadeClose: true,
        content: `../../../addDetails/addProject/constructionUnit/constructionUnit.html`
    });
    console.log(localStorage.getItem("realName"));
    $(this).val(localStorage.getItem("realName"))
});
/*********点击确定按钮，将信息保存到后台****************/

/*$('.resure').click(function () {
 resure();

 });*/
// $('input[type="text"]');

/******封装 ---获取页面填写信息并发送*********/
//